package com.lzx.shop.service.impl;

import com.aliyun.oss.OSS;
import com.lzx.shop.config.OssConfig;
import com.lzx.shop.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 刘正星
 * @version 1.0.0
 * @ClassName OssServiceImpl.java
 * @Description Oss文件服务
 * @createTime 2021年04月10日 20:57:00
 */
@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OssConfig ossConfig;
    @Autowired
    private OSS ossClient ;

    private final String img = "bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp,avif";

    private final String office = "docdocxdocmdotxdotxxlsxxlsmxltxpptxppt";
    @Override
    public String upload(MultipartFile multipartFile) {

        String  fileName = multipartFile.getOriginalFilename();
        // 按日期存储
        //String fileAddress = new Date().toString();
        //重新命名文件
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String newFileName = +System.currentTimeMillis()+ "." + suffix;

        // 获得文件流
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String directory = "";

        if (img.indexOf(suffix)!=-1) {
            directory = "images/";
        }else if (suffix.equals("pdf")){
            directory = "pdf/";
        }else if (office.indexOf(suffix)!=-1){
            directory= "office文件/";
        }else{
            directory = "other";
        }

        // 上传到OSS
        ossClient.putObject("liuzhengxing", directory + newFileName, inputStream);
        //关闭oss流
        //ossClient.shutdown();

        String  url= "https://liuzhengxing.oss-cn-hangzhou.aliyuncs.com/"+directory+ newFileName;

        return url;
    }

    @Override
    public boolean delete(String fileName) {
        String sufix = fileName.substring(fileName.lastIndexOf(".")+1);
        String file  = fileName.substring(fileName.lastIndexOf("/")+1);
        if (img.indexOf(sufix)!=-1){
            file = "images/"+file;
        }

        System.out.println(file);
        ossClient.deleteObject(ossConfig.getBucketName(),file);
        return true;
    }

}
